import {
	getSCartList,
	countChange,
	delSCart,
	deleteCartBatch
} from '@/api/sCart'
export default {
	namespaced: true,
	state() {
		return {
			sCartList: {},
			selectedList: []
		}
	},
	mutations: {
		setsCartList(state, sCartList) {
			state.sCartList = sCartList
		},
		setSelectedList: (state, selectedList) => {
			// 修改selectList
			state.selectedList = selectedList
			// console.log(state.selectedList)
		},
		pushSelectedList: (state, cartObj) => {
			cartObj.selected = true
			console.log(state.selectedList)
			// 添加到selectList，如果有重复的商品，增加count
			let selectedCartObj = state.selectedList.find((item) => {
				if (item.spuId === cartObj.spuId) {
					return true
				}
			})
			if (selectedCartObj) {
				selectedCartObj.count += cartObj.count
			} else {
				state.selectedList.push(cartObj)
			}
		}
	},
	actions: {
		async getSCartListAction(context, userId) {
			const { data } = await getSCartList(userId)
			//每个商品的选中状态
			data.forEach((item) => {
				item.selected = false
			})
			context.commit('setsCartList', data)
		},
		async countChange(context, { id, userId, count }) {
			await countChange(id, userId, count)
		},
		async delSCart(context, { userId, id }) {
			await delSCart(userId, id)
		},
		async delSCartBatch(context, { userId, ids }) {
			await deleteCartBatch({ userId: userId, ids: ids })
		}
	},
	getters: {}
}
